/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-06-20 09:37:07
 * @LastEditors: cuidm
 * @LastEditTime: 2022-06-28 17:25:21
 */
import React, { useState, useEffect, Fragment } from "react";
import { message, Drawer, Form, Select, Space, Button, Modal } from "antd";;
import { HcpTableTransfer } from "@/components";
import cmdbres from "@/data/cmdbres";
import request from "@/utils/request";
import hcpUtils from "@/utils/hcpUtils";

const user = hcpUtils.getUser(); 
const RelationTagModal = ({id, info, visible, setVisible, onRelationFinish}) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [tagData, setTagData] = useState([]);
    const [targetKeys, setTargetKeys] = useState([]);
    const leftTableColumns = [
        {
            title: "标签名称",
            displayName:'可关联标签',
            key: "tagName",
            dataIndex: "tagName",
            width: 140,
            showTotal: true,
            ellipsis: { showTitle: true },
        },
        {
            title: "标签标识",
            key: "tagCode",
            dataIndex: "tagCode",
        },
    ];
    const rightTableColumns = [
        {
            title: "标签名称",
            displayName:'已关联标签',
            key: "tagName",
            dataIndex: "tagName",
            width: 140,
            showTotal: true,
            ellipsis: { showTitle: true },
        },
        {
            title: "标签标识",
            key: "tagCode",
            dataIndex: "tagCode",
        },
    ];

    const getTagData = async (tags) => {
        try {
            const res = await request({
                ...cmdbres.queryTags,
                data: {
                    queryFilter: {
                        EQ:{
                            status: 0
                        }
                    },
                    sort:{
                        create_time: "DESC"
                    },
                },
            });
            if (res && res.data) {
                res.data.map((item, index) => {
                    item.key = item.tagCode;
                    const tag = tags?.find(v=> v.woIsdeleted == 'N' && v.tagCode == item.tagCode);
                    item.relationId = tag && tag.id;
                });
                setTagData(res.data);
            } else {
                setTagData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    const onFinish = async () => {
        setLoading(true);
        if(addTags.length == 0 && deleteTags.length == 0) {
            setVisible(false);
            return;
        }
        if(addTags.length) relationTag();
        if(deleteTags.length) deleteRelationTag();
        setLoading(false);
        setVisible(false);
    };

    const relationTag = async() => {
        let data = [];
        addTags.map(item=> {
            data.push({
                resourceCmUnid: info.cm_unid,
                tagCode: item.tagCode,
                tagName: item.tagName,
                author: user.staffName
            })
        })
        let res = await request({
            ...cmdbres.relationTag,
            data
        });
        if (res && res.code == 200) {
            message.success("关联标签成功！");
            if (typeof onRelationFinish == "function") onRelationFinish();
        } else {
            if(res) message.error(res.msg);
        }
    }

    const deleteRelationTag = async() => {
        const ids = deleteTags.map(item=> item.relationId);
        let res = await request({
            ...cmdbres.deleteRelationTag(ids),
            params: {
                author: user.staffName
            }
        });
        if (res && res.code == 200) {
            message.success("取消关联标签成功！");
            if (typeof onRelationFinish == "function") onRelationFinish();
        } else {
            if(res) message.error(res.msg);
        }
    }

    useEffect(() => {
        if(visible && info) {
            let tagIds = new Set();
            info.tagRelations?.map(item => {
                if(item.woIsdeleted == 'N')
                    tagIds.add(item.tagCode)
            });
            tagIds = [...tagIds];
            setTargetKeys(tagIds);
            getTagData(info.tagRelations);
        } 
    }, [visible, info])

    const handleClose = () => {
        setVisible(false);
    }

    const [addTags, setAddTags] = useState([]);
    const [deleteTags, setDeleteTags] = useState([]);
    const onChange = (keys) => {
        // console.log('onChange',tagData, keys);
        let addArr = [];
        let deleteArr = [];
        tagData.map(item => {
            if(item.relationId && !keys.includes(item.tagCode)) {
                deleteArr.push(item);
            };
            if(!item.relationId && keys.includes(item.tagCode)) {
                addArr.push(item);
            }
        })
        setAddTags(addArr);
        setDeleteTags(deleteArr);
    };
    
    return (
        <Drawer 
            className="drawer-table-columns create-field"
            title={'关联标签'}
            placement={'right'}
            width={800}
            onClose={handleClose}
            visible={visible}
            footer={null}
        >
			<Form
                className="hcp-drawer-form"
				form={form}
				labelCol={{ span: 3 }}
				wrapperCol={{ span: 21 }}
				name="basic"
				onFinish={onFinish}
			>
                <Form.Item label="标签" name="tag">
                    <HcpTableTransfer
                        dataSource={tagData}
                        targetKeys={targetKeys}
                        leftColumns={leftTableColumns}
                        rightColumns={rightTableColumns}
                        leftLengthMax={5}
                        rightLengthMax={5}
                        pagination={false}
                        onChange={onChange}
                    />
                </Form.Item>
                <Form.Item label="待关联标签" name="add">
                    <Space>
                    {addTags.length ? addTags.map((item, index)=> (
                            <Button key={index} type="primary">{item.tagName}&nbsp;&nbsp;</Button>
                    )): "无"}
                    </Space>
                </Form.Item>
                <Form.Item label="待取消标签" name="delete">
                    <Space>
                    {deleteTags.length ? deleteTags.map((item, index)=> (
                        <Button key={index} type="primary">{item.tagName}&nbsp;&nbsp;</Button>
                    )): "无"}
                    </Space>
                </Form.Item>
                
                <div className="modal-body-footer">
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
                        <Button onClick={handleClose}>取消</Button>
                    </Space>
                </div>
			</Form>
		</Drawer>
    )
};

export default RelationTagModal;
